#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/print_sys_info.sh"

APP_TARGET_DIR_NAME="voxcpm"

export CURRENT_APP_PATH="$LMD_APPS_DIR/$APP_TARGET_DIR_NAME"
echo "App Dir: ${CURRENT_APP_PATH}"

cd "$CURRENT_APP_PATH"

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp"
CONDA_PREFIX="./venv"

echo "use ./venv to start app."
export HF_HOME="$CURRENT_APP_PATH/tmp_hf_home"
export MODELSCOPE_HOME="$CURRENT_APP_PATH/tmp_modelscope_home"
export MODELSCOPE_CACHE="$CURRENT_APP_PATH/tmp_modelscope_cache"

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True

if [ "$LMD_LAUNCH_APP_MODULE" = "cpu-mode" ]; then
  export CUDA_VISIBLE_DEVICES="-1"
fi

APP_FILE_NAME=app.py
if [ -n "$GRADIO_SERVER_PORT" ]; then
  ORIGINAL_FILE=$APP_FILE_NAME
  NEW_FILE=app_temp.py
  sed "s/run_demo()/run_demo(server_port=$GRADIO_SERVER_PORT)/g" "$ORIGINAL_FILE" > "$NEW_FILE"
  APP_FILE_NAME=$NEW_FILE
  echo "- APP_FILE_NAME: $APP_FILE_NAME"
  echo "- PORT: $PORT"
fi

conda run -p $CONDA_PREFIX --no-capture-output python $APP_FILE_NAME $PORT_PARAM
